from lib.net import wifi
import time
import re
from lib.sensors.oled import ops
import sys
import gc
from lib.sensors import soil_humidity, ws2812
import json


def visit_echo_html():
    resp = wifi.GET("echo.free.beeceptor.com")
    print(resp)


def visit_hanxiaoxin_html():
    resp = wifi.GET("www.hanxiaoxin.cn")
    print(resp)


def visit_hanxiaoxin_room_html():
    resp = wifi.GET("www.hanxiaoxin.cn", "/room", 3000)
    print(resp)


def visit_hanxiaoxin_msg_html():
    resp = wifi.GET("www.hanxiaoxin.cn", "/msg", 3000)
    print(resp)


def visit_hanxiaoxin_room():
    resp = wifi.GET("www.hanxiaoxin.cn", "/msg", 3000)
    json_str = resp.decode()
    # print(len(json_str))
    # print(json_str)
    json_str = json_str.replace("CLOSED", "")
    json_str = re.sub(r"\+IPD,\d+:", "", json_str)

    try:
        with open("msg.json", "w") as outfile:
            outfile.write(json_str)
        match = re.search(r"\{(.*?)\}", json_str)
        if match:
            v = "{" + match.group(1) + "}"
            json_data = json.loads(v)
            msg = json_data["msg"]
            font12 = json_data["font12"]
            # print(msg)
            # print(font12)
            ops.set_font(font12, 12)
            ops.reset_line()
            ops.show_text(msg)
    except Exception as e:
        print(e)

    # ops.reset_line()
    # ops.show_text(v)


def visit_hanxiaoxin(count=0):
    ops.show_text("connect wifi...")
    ops.show_text("connect ok...")
    try:
        if count > 0:
            visit_hanxiaoxin_room()
        else:
            while True:
                gc.collect()
                free_m = gc.mem_free()
                alloc_m = gc.mem_alloc()
                print("free: ", free_m / 1024, "KB alloc_m: ", alloc_m / 1024, "KB")
                visit_hanxiaoxin_room()
                time.sleep(15)
    except Exception as e:
        time.sleep(5)
        visit_hanxiaoxin()


delay = 0.5
font_size = 12
loop = False


def http_demo():
    try:
        # visit_hanxiaoxin()
        # visit_echo_html()
        visit_hanxiaoxin_msg_html()
    except Exception as e:
        with open("log.txt", "a+") as f:
            f.write(str(e))
            f.write("\n")
        sys.print_exception(e)


def tcp_demo():
    payload = {
        "op": "upload",
        "topic": "Tiot_3WRKsAs5",
        "name": "dataset",
        "data": "4,3,2,1",
    }
    wifi.POST_RAW(payload, "creation-hardware.codemao.cn", "/", 3000)


def soil_demo(loop=False):
    payload = {
        "op": "upload",
        "topic": "Tiot_3WRKsAs5",
        "name": "dataset",
        "data": "",
    }
    if loop:
        while loop:
            humidity = soil_humidity.read_humidity()
            payload["data"] = f"bao an,humidity,{humidity}%"
            wifi.POST_RAW(payload, "creation-hardware.codemao.cn", "/", 3000)
            time.sleep(20)
    else:
        humidity = soil_humidity.read_humidity()
        payload["data"] = f"bao an,humidity,{humidity}%"
        wifi.POST_RAW(payload, "creation-hardware.codemao.cn", "/", 3000)


def ws2812_demo():
    global loop
    ws2812.condition_show(loop)


DEMO_DICT = {
    "HTTP": http_demo,
    "TCP": tcp_demo,
    "WS2812": 2,
    "SOIL": soil_demo,
}

callback = DEMO_DICT["HTTP"]

if callback:
    callback()
